package com.ruoyi.web.controller.tool;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.domain.FileExportVo;
import com.ruoyi.web.domain.ResultInfo;
import com.ruoyi.web.service.MongoFileService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;

@RestController
@RequestMapping("/mongodb")
public class MongodbController extends BaseController {
    @Resource
    MongoFileService mongoFileService;

    /**
     * 文件上传
     * @param file
     * @param type
     * @return
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam(value = "file") MultipartFile file,
                                 @RequestParam("type") Integer type,
                                 HttpServletRequest request) {
        try {
            return success(mongoFileService.uploadFile(file, type,request));
        } catch (Exception e) {
            System.out.println(e);
            return error(e.getMessage());
        }
    }
    /**
     * 文件下载
     * @param fileId
     * @return
     */
    @GetMapping("/download/{fileId}")

    public ResponseEntity<Object> fileDownload(@PathVariable(name = "fileId") Long fileId) {
        FileExportVo fileExportVo = mongoFileService.downloadFile(fileId);

        if (Objects.nonNull(fileExportVo)) {
            HttpHeaders headers = new HttpHeaders();
            String encodedFileName = null;
            try {
                encodedFileName = URLEncoder.encode(fileExportVo.getFileName(), StandardCharsets.UTF_8.toString());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName);
            headers.setContentType(MediaType.parseMediaType(fileExportVo.getContentType()));
            headers.setContentLength(fileExportVo.getFileSize());
            headers.set("Connection", "close");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileExportVo.getData());
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("file does not exist");
        }
    }

    /**
     * 文件删除
     * @param fileId
     * @return
     */
    @GetMapping("/remove/{fileId}")
    public AjaxResult removeFile(@PathVariable(name = "fileId") Long fileId) {
        mongoFileService.removeFile(fileId);
        return success("删除成功");
    }
}
